import React from 'react';
import { Spin } from 'antd';
import { isEqual, isEmpty } from 'lodash';
import { WeaErrorPage, WeaTools,WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const { ls } = WeaTools;
import Title from './Title';
import MarqueeCom from '../common/MarqueeCom';
import NewsType from './NewsType';
import {formatDate, openLinkUrl} from "../../util/common";
//内容组件
class EContent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tabdata: props.edata.data,
            currentTab: props.edata.currenttab,
            refresh: false,
        }
        this.toggleTabPage = this.toggleTabPage.bind(this);
        this.handleTabData = this.handleTabData.bind(this);
        this.canOnclick = this.canOnclick.bind(this);
        this.handleOpen = this.handleOpen.bind(this);
        if(window.element_news_refresh && typeof element_news_refresh == 'object'){
            window.element_news_refresh[props.config.params.eid] = this.handleTabData.bind(this);
        }else{
            let obj = {};
            obj[props.config.params.eid] = this.handleTabData.bind(this);
            window.element_news_refresh = obj
        }
    }
    componentWillMount(){
        this.canOnclick();
    }
    componentWillReceiveProps(nextProps){
        if(!isEqual(nextProps, this.props)){
            this.setState({
                tabdata: nextProps.edata.data,
                currentTab: nextProps.edata.currenttab,
                refresh: false,
            });
        }
    }
    shouldComponentUpdate(nextProps, nextState){
        return !isEqual(this.state, nextState) || !isEqual(this.props, nextProps)
    }
    componentDidMount(){
        this.props.onRef(this);
    }
    toggleTabPage(tabid){
        const { currentTab } = this.state;
        this.setState({
            refresh: !(tabid === currentTab),
        });
        this.handleTabData(tabid);
    }

    handleTabData(tabid){
        const { params, isremembertab } = this.props.config;
        this.setState({
            currentTab: tabid,
            tabdata: ls.getJSONObj('tabdata-' + params.eid + '-' + tabid),
        });
        WeaTools.callApi('/api/portal/element/newstab', 'POST', {...params, tabid}).then(result => {
            ls.set('tabdata-' + params.eid + '-' + tabid, result);
            if(tabid === this.state.currentTab){
                this.setState({
                    tabdata: result,
                    refresh: false,
                });
                if(isremembertab){
                    let edata = ls.getJSONObj('edata-' + params.eid);
                    if(edata){
                        edata.currenttab = tabid;
                        edata.data = result;
                        ls.set('edata-' + params.eid, edata);
                    }
                }
            }
        });
    }
    handleOpen(){
        const { tabdata } = this.state;
        const { tabsetting = {} } = tabdata;
        const { catalogId, catalogIds } = tabsetting;
        if(catalogId){
            openLinkUrl('/spa/document/index.jsp?secid='+catalogId+'&isEdit=1&moudleFrom=portal','2');
        }else{
            openLinkUrl('/spa/document/static/index.html#/main/document/add?openNewWindow=0&moudleFrom=portal&secids='+catalogIds,'2');
        }
    }
    canOnclick(currentTab = this.state.currentTab){
        const { config, edata, onChangeCanEdit } = this.props;
        const { tabdata = {} } = this.state;
        const { data } = edata;
        const { eid } = config.params;
        const { docParams ={} } = tabdata;
        const { docCatalogIds } = docParams;
        if(docCatalogIds && docCatalogIds.length > 0){
            let rightArr = ls.getJSONObj('portal-doc-right');
            let params = {ids: docCatalogIds.join()};
            if(rightArr == null){
                WeaTools.callApi('/api/portal/elementsetdoc/docsetright', 'POST', params).then(result => {
                    let right = result.canEdit == 'true' ? true : false ;
                    onChangeCanEdit(right);
                    ls.set('portal-doc-right', [{eid: eid, tabid: currentTab, data: formatDate(new Date(), "yyyy-MM-dd"),right: right}]);
                });
            }else{
                let isHave = false;
                rightArr.map((item)=>{
                    if(item.eid == eid && item.tabid == currentTab){
                        onChangeCanEdit(item.right);
                        isHave = true;
                        return;
                    }
                });
                if(!isHave){
                    WeaTools.callApi('/api/portal/elementsetdoc/docsetright', 'POST', params).then(result => {
                        let right = result.canEdit == 'true' ? true : false ;
                        onChangeCanEdit(right);
                        rightArr.push({eid: eid, tabid: currentTab,data: formatDate(new Date(), "yyyy-MM-dd"), right: right });
                        ls.set('portal-doc-right', rightArr);
                    });
                }
            }
        }else {
            onChangeCanEdit(false);
        }
    }
    render() {
        const { config, edata, handleRefresh, handleDelete, fontSizeMp, onChangeShowAdd } = this.props;
        const { tabdata, currentTab, refresh } = this.state;
        const { tabids = [], titles =[], counts,esetting={} } = edata;
        const { eid } = config.params;
        let { fontStyle,header} = config.item;
        const { contentview = {} } = config.item;
        if(!isEmpty(fontSizeMp)) fontStyle = fontSizeMp;
        esetting.fontStyle = fontStyle;
        let cstyle = {height: contentview.style.height,overflow: "auto"};
        if(header.displayPosition && header.displayPosition == 'bottom'){
            if(tabids && tabids.length > 1 || tabids && tabids.length == 1 && esetting.isAlwaysShow=='1'){
                if(contentview.style.height){
                    cstyle = {height: parseInt(contentview.style.height)-32+"px",overflow: "auto"};
                }else {
                    cstyle = {height: contentview.style.height,overflow: "auto"};
                }
            }
        }
        let contentHtml = <div/>;
        let more = '';
        let tabdata_img = {};
        if(!isEmpty(tabdata)){
            tabdata_img = _.cloneDeep(tabdata);
            tabdata_img.tabsetting.imgs=[];
        }
        if (tabdata) {
            more = tabdata.tabsetting.more;
            contentHtml = <MarqueeCom ecId={`${this && this.props && this.props.ecId || ''}_MarqueeCom@pz1a1b`} tabdata={!refresh ? tabdata: tabdata_img} eid={eid} scolltype={tabdata.tabsetting.rollDirection}><NewsType ecId={`${this && this.props && this.props.ecId || ''}_NewsType@kpdnju`} eid={eid} data={!refresh ? tabdata: tabdata_img} esetting={esetting} /></MarqueeCom>
        }
        const _titleProps = {
            currentTab,
            config,
            titles,
            counts,
            tabids,
            handleRefresh,
            handleDelete,
            more,
            fontSizeMp,
            tabwidth: esetting.tabwidth,
            methodvalue: esetting.methodvalue,
            isAlwaysShow: esetting.isAlwaysShow,
            tabstyle: esetting.tabstyle,
            tabvalue: esetting.tabvalue,
            handleTabData: this.toggleTabPage,
        }
        return <div>
            <Title ecId={`${this && this.props && this.props.ecId || ''}_Title@33htxc`} {..._titleProps}/>
            <div className="tabContant" id={`tabcontant_${eid}`} onMouseOver={() => {
                this.canOnclick();
                onChangeShowAdd(true)
            }} style={{height: cstyle.height}} onMouseLeave={() => onChangeShowAdd(false)}>
                <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@2pmxn0`} spinning={refresh}>{contentHtml}</Spin>
            </div>
        </div>;
    }
}

class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return ( <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@j5e0zc`} msg = { hasErrorMsg ? this.props.error : getLabel(385218,"对不起，该页面异常，请联系管理员！") }/>
        );
    }
}
EContent = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(EContent);
export default EContent;
